# coding: utf-8

import json
import time
from datetime import datetime
from tornado.httpclient import HTTPError
import tornado.process
from tornado.httpclient import AsyncHTTPClient
from tornado import gen
from util.PyMysql import PyMysql
from util.time_transform import str2unix
from util.logConf import log
from util.my_error import InfluxdbError

class InfluxdbHandler(tornado.web.RequestHandler):
    @gen.coroutine
    def query_influxdb(self, query):
        client = AsyncHTTPClient()
        log.debug(query)
        try:
            response = yield client.fetch(query)
        except ConnectionRefusedError as e:
            log.error(e.args)
            log.error(query)
            raise InfluxdbError("ConnectionRefusedError when  connect to  influxdb:{} ".format(query))
        except HTTPError as e:
            log.error(query)
            log.error(e)
            log.error(e.args)
            raise InfluxdbError('HTTPError:{} when connect to influxdb:{}'.format(e.code, query))
        except OSError as e:
            log.error(e)
            log.error(e.args)
            raise InfluxdbError('OSError when connect to influxdb:{}'.format(query))
        return response.body

    def get_fidis_ip(self, fidis_name, clientid):
        if not fidis_name:
            sql = "SELECT username FROM gards_aprus WHERE clientid=%s"
            my_sql = PyMysql()
            result = my_sql.select(sql, (clientid,))
            if result:
                fidis_name = result.get('username')
                if not fidis_name:
                    fidis_name = 'mixlinker'
            else:
                fidis_name = 'mixlinker'

        log.info(fidis_name)
        log.info(clientid)
        sql = "SELECT ip from gards_fidis_ip WHERE  fidis_id = %s"
        my_sql = PyMysql()
        result = my_sql.select(sql, (fidis_name, ))
        if result:
            ip = result.get('ip')
        else:
            dt = {
                "success": False,
                "error": '找不到该设备存储的IP,可能是无效的clientid或者fidis_name'
            }
            self.write(json.dumps(dt))
            self.set_status(400)
            return self.finish()
        return fidis_name, ip

    @staticmethod
    def get_result_columns_values(body, index=0):
        res_dict = json.loads(body)
        result_list = res_dict.get('results')
        result = result_list[index]
        series = result.get("series")
        if series:
            columns = series[0].get("columns")
            values = series[0].get("values")
            return [columns, values]



    @staticmethod
    def str2unix(time_str, format_str="%Y-%m-%d %H:%M:%S"):
        if time_str:
            date = datetime.strptime(time_str, format_str)
        else:
            date = datetime.now()
        unix_time = "{}000000000".format(int(time.mktime(date.timetuple())))
        return unix_time

    @staticmethod
    def unix2str(unix, format_str="%Y-%m-%d %H:%M:%S"):
        if not unix:
            return "unknown"
        unix_int = int(unix)
        time = datetime.fromtimestamp(unix_int)
        time_str = time.strftime(format_str)
        return time_str

    def verify_date(self, start_date, end_date, allow_start_null, allow_end_null):
        if not (allow_start_null or start_date):
            self.write(json.dumps({"success": False, "error": "need start_date"}))
            self.set_status(400)
            return self.finish()
        if not (allow_end_null or end_date):
            self.write(json.dumps({"success": False, "error": "need end_date"}))
            self.set_status(400)
            return self.finish()
        try:
            unix_start = str2unix(start_date)
            unix_end = str2unix(end_date)
        except ValueError as e:
            dt = {
                "success": False,
                "error": e.args
            }
            self.write(json.dumps(dt))
            self.set_status(400)
            return self.finish()
        return unix_start, unix_end